package com.zhu.storesmanager.network;

import java.util.List;

import com.zhu.storesmanager.models.SyncModel;
import com.zhu.storesmanager.provider.StoresManagerSettings;
import com.zhu.storesmanager.utils.Log;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

/**
 * 同步数据结果保存
 */
public class SyncUtil {

	public static String[] PROJECTION = new String[]{ "_id" };  //查询PROJECTION

	/**
	 * 保存所有型号数据至数据库
	 * @param context 上下问
	 * @param productResult 型号结果
	 * @param isFirstSync 是否第一次同步
	 */
	public static void saveModelList(Context context,  SyncModel.ProductResult productResult, boolean isFirstSync){
//		String where = "";
//		if(productResult.Data.Deled != null && productResult.Data.Deled.size() > 0){ //检查需要删除的型号数据
//			for(int i = 0; i < productResult.Data.Deled.size(); i++){ //遍历所有删除型号数据  生成删除条件
//				if(where.length() == 0){
//					where = getQueryWhere(StoresManagerSettings.ModelsColumns.MODELS_NAME, productResult.Data.Deled.get(i));
//				}else{
//					where += " or " +getQueryWhere(StoresManagerSettings.ModelsColumns.MODELS_NAME, productResult.Data.Deled.get(i));
//				}
//			}
//		}
//		if(where != null && where.length() > 0){ //删除型号
//			context.getContentResolver().delete(StoresManagerSettings.ModelsColumns.CONTENT_URI, where, null);
//		}
//		if(isFirstSync){ //第一次同步删除所有数据
//		    context.getContentResolver().delete(StoresManagerSettings.ModelsColumns.CONTENT_URI, null, null);
//		}
		if(productResult.Models != null && productResult.Models.size() > 0){ //更新型号数据
			context.getContentResolver().delete(StoresManagerSettings.ModelsColumns.CONTENT_URI, null, null);
			ContentValues values = new ContentValues();
			for(String model : productResult.Models){ //遍历所有型号数据 插入本地数据库
				values.clear();
//				if(isFirstSync){ //第一次同步则直接插入所有数据
				    values.put(StoresManagerSettings.ModelsColumns.MODELS_NAME, model);
                    context.getContentResolver().insert(StoresManagerSettings.ModelsColumns.CONTENT_URI_NO_NOTIFICATION, values);
//				}else{//不是第一次
//				    long dbid = getDatabaseId(context, StoresManagerSettings.ModelsColumns.CONTENT_URI_NO_NOTIFICATION, 
//	                        getQueryWhere(StoresManagerSettings.ModelsColumns.MODELS_NAME, model)); //检查数据是否存在
//	                if(dbid == -1){ //不存在则插入
//	                    values.put(StoresManagerSettings.ModelsColumns.MODELS_NAME, model);
//	                    context.getContentResolver().insert(StoresManagerSettings.ModelsColumns.CONTENT_URI_NO_NOTIFICATION, values);
//	                }else{ //存在 则跳过
//	                    Log.e(model + " already exist in the database");
//	                }
//				}
			}
		}
	}

	/**
     * 保存数据词典数据至数据库
     * @param context 上下问
     * @param dictResult 数据词典数据
     * @param isFirstSync 是否第一次同步
     */
    public static void saveDictsList(Context context,  SyncModel.DictResult dictResult, boolean isFirstSync){
        if(isFirstSync){ //第一次同步删除所有数据
            context.getContentResolver().delete(StoresManagerSettings.DataDictionaryColumns.CONTENT_URI, null, null);
        }
        ContentValues values = new ContentValues();
        for(SyncModel.ResDict dict : dictResult.Data){ //遍历所有数据
            int typeid = dict.TypeId;
            if(!isFirstSync){ //不是第一次同步先删除所有typeid类型数据
                String where = StoresManagerSettings.DataDictionaryColumns.DATA_TYPE + "=" + typeid;
                context.getContentResolver().delete(StoresManagerSettings.DataDictionaryColumns.CONTENT_URI_NO_NOTIFICATION, where, null);   
            }
            for(String sn : dict.Items){ //插入每条数据
                values.clear();
                values.put(StoresManagerSettings.DataDictionaryColumns.DATA_TYPE, typeid);
                values.put(StoresManagerSettings.DataDictionaryColumns.DATA_NAME, sn);
                context.getContentResolver().insert(StoresManagerSettings.DataDictionaryColumns.CONTENT_URI_NO_NOTIFICATION, values);
            }
        }
    }

    /**
     * 保存拜访数据项标签至数据库
     * @param context 上下问
     * @param projectResult 数据
     * @param isFirstSync 是否第一次同步
     */
    public static void saveProjectsList(Context context,  SyncModel.ProjectResult projectResult, boolean isFirstSync){
        if(isFirstSync){ //第一次同步删除所有数据
            context.getContentResolver().delete(StoresManagerSettings.DataProjectsColumns.CONTENT_URI, null, null);
        }
        ContentValues values = new ContentValues();
        for(SyncModel.ResProject project : projectResult.Data){ //遍历所有数据
            int typeid = project.TypeId;
            if(!isFirstSync){ //不是第一次同步先删除所有typeid类型数据
                String where = StoresManagerSettings.DataDictionaryColumns.DATA_TYPE + "=" + typeid;
                context.getContentResolver().delete(StoresManagerSettings.DataProjectsColumns.CONTENT_URI_NO_NOTIFICATION, where, null);   
            }
            for(SyncModel.ResProjectItem item : project.Items){ //插入每条数据
                values.clear();
                values.put(StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE, typeid);
                //values.put(StoresManagerSettings.DataProjectsColumns.PROJECT_NAME, project.TypeName);
                values.put(StoresManagerSettings.DataProjectsColumns.ITEM_NAME, item.Name);
                values.put(StoresManagerSettings.DataProjectsColumns.ITEM_SAVE, item.IsSave ? 1 : 0);
                values.put(StoresManagerSettings.DataProjectsColumns.ITEM_SHOW, item.IsShow ? 1 : 0);
                values.put(StoresManagerSettings.DataProjectsColumns.ITEM_SEQUENCE, item.Sequence);
                context.getContentResolver().insert(StoresManagerSettings.DataProjectsColumns.CONTENT_URI_NO_NOTIFICATION, values);
            }
        }
    }

    /**
     * 保存拜访数据项标签至数据库
     * @param context 上下问
     * @param reminderResult 数据
     * @param isFirstSync 是否第一次同步
     */
    public static void saveRemindList(Context context,  SyncModel.ReminderResult reminderResult, boolean isFirstSync){
        //context.getContentResolver().delete(StoresManagerSettings.RemindsColumns.CONTENT_URI_NO_NOTIFICATION, null, null);
        if(reminderResult.Data != null)
        {
            ContentValues values = new ContentValues();
            for(SyncModel.ResReminder reminder : reminderResult.Data)
            {
                values.clear();
                values.put(StoresManagerSettings.RemindsColumns.MESSAGEID, reminder.Id);
                values.put(StoresManagerSettings.RemindsColumns.TYPE, reminder.Type);
                values.put(StoresManagerSettings.RemindsColumns.CUSTOMERID, reminder.CounterCode);
                values.put(StoresManagerSettings.RemindsColumns.TEXT, reminder.Content);
                values.put(StoresManagerSettings.RemindsColumns.DEADTIME, reminder.Deadline.getTime());
                values.put(StoresManagerSettings.RemindsColumns.TIME, reminder.RemindDate.getTime());
                values.put(StoresManagerSettings.RemindsColumns.RANGENAME, reminder.RangeName);
                long dbid = getDatabaseId(context, StoresManagerSettings.RemindsColumns.CONTENT_URI_NO_NOTIFICATION, 
                        StoresManagerSettings.RemindsColumns.MESSAGEID + "=\'" + reminder.Id + "\'"); //检查数据是否存在
                if(dbid == -1){ //不存在则插入
                	context.getContentResolver().insert(StoresManagerSettings.RemindsColumns.CONTENT_URI_NO_NOTIFICATION, values);
                }else{
                	context.getContentResolver().update(StoresManagerSettings.RemindsColumns.getContentUri(dbid, false), values, null, null);
                }
            }                   
        }
    }

    /**
     * 保存拜访数据项标签至数据库
     * @param context 上下问
     * @param visitResult 数据
     * @param isFirstSync 是否第一次同步
     */
    public static void saveVisitTaskList(Context context, SyncModel.VisitResult visitResult,
            boolean isFirstSync) {
    	ContentValues values = new ContentValues();
    	values.put(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_LAST, 1);
    	context.getContentResolver().update(StoresManagerSettings.SupervisorStorePromoterColumns.CONTENT_URI_NO_NOTIFICATION, values, null, null);
        if (visitResult.Data != null) {
            for (SyncModel.ResVisit visit : visitResult.Data) {
                values.clear();
                values.put(StoresManagerSettings.SupervisorVisitTaskColumns.STOREID, visit.CounterCode);
                values.put(StoresManagerSettings.SupervisorVisitTaskColumns.STORENAME, visit.CounterName);
                values.put(StoresManagerSettings.SupervisorVisitTaskColumns.VISITID, visit.Id);
                values.put(StoresManagerSettings.SupervisorVisitTaskColumns.VISITDATA, visit.VisitDate.getTime());
                long dbid = getDatabaseId(context, StoresManagerSettings.SupervisorVisitTaskColumns.CONTENT_URI_NO_NOTIFICATION, 
                        StoresManagerSettings.SupervisorVisitTaskColumns.VISITID + "=" + visit.Id); //检查数据是否存在
                if(dbid == -1){ //不存在则插入
                    context.getContentResolver().insert(StoresManagerSettings.SupervisorVisitTaskColumns.CONTENT_URI_NO_NOTIFICATION, values);
                }
                if(visit.Promoters != null)
            	{
            		for(SyncModel.ResVisitPromoter promoter : visit.Promoters)
            		{
            			values.clear();
            			long pdbid = getDatabaseId(context, StoresManagerSettings.SupervisorStorePromoterColumns.CONTENT_URI_NO_NOTIFICATION, 
            					StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_ID + "=\'" + promoter.PromoterCode + "\' AND " +
            					StoresManagerSettings.SupervisorStorePromoterColumns.STOREID +"=\'" + visit.CounterCode +"\'"); //检查数据是否存在
                        if(pdbid == -1){ //不存在则插入
                        	values.put(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_ID, promoter.PromoterCode);
                			values.put(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_NAME, promoter.PromoterName);
                			values.put(StoresManagerSettings.SupervisorStorePromoterColumns.STOREID, visit.CounterCode);
                			context.getContentResolver().insert(StoresManagerSettings.SupervisorStorePromoterColumns.CONTENT_URI_NO_NOTIFICATION, values);	
                        }else{
                        	values.put(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_NAME, promoter.PromoterName);
                        	values.put(StoresManagerSettings.SupervisorStorePromoterColumns.PROMOTER_LAST, 0);
                        	context.getContentResolver().update(StoresManagerSettings.SupervisorStorePromoterColumns.getContentUri(pdbid, false), values, null, null);	
                        }            			
            		}
            	}
            }
        }
    }

	public static String getQueryWhere(String name, String text){
		return name + "=\'"+text + "\'";
	}

	/**
	 * 获取数据库主键ID
	 * @return id  -1 查询失败 >-1查询成功
	 */
	public static long getDatabaseId(Context context, Uri uri, String where){
    	long id = -1;
    	Cursor cursor = null;
    	try{
    		cursor = context.getContentResolver().query(uri, PROJECTION, where, null, null);
    		if(cursor.getCount() > 0 && cursor.moveToFirst()){
    			id = cursor.getLong(cursor.getColumnIndexOrThrow("_id"));
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		if(cursor != null){
    			cursor.close();
    			cursor = null;
    		}
    		return id;
    	}
    }
}
